package com.haobo.service.impl;

import com.haobo.dao.RoleDao;
import com.haobo.dao.UserDao;
import com.haobo.pojo.Role;
import com.haobo.pojo.User;
import com.haobo.service.UserService;
import org.springframework.dao.EmptyResultDataAccessException;

import java.util.List;

/**
 * ClassName:UserServiceImpl
 * Package:com.haobo.service.impl
 * Description:
 *
 * @Date:2021/5/28 20:51
 * @Author:haobo
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    private RoleDao roleDao;
    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    @Override
    public List<User> list() {
        List<User> userList = userDao.findAll();
        //为userList中的每一个user封装roles数据
        for (User user : userList) {
            //获取userId
            Long id = user.getId();
            //通过userId查询当前user对应的Role数据集合
            List<Role> roles = roleDao.findRoleByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }

    @Override
    public void user_add(User user, Long[] roleIds){
        //第一步向sys_user表中存储数据
        Long userId = userDao.userAdd(user);
        //第二部向sys_user_role关系表中存储多条数据
        userDao.urAdd(userId,roleIds);
    }

    @Override
    public void delUser(Long userId) {
        //1、删除sys_user_role关系表
        userDao.delUserRoleRel(userId);
        //2、删除sys_user表
        userDao.delUser(userId);
    }

    @Override
    public User user_login(String username, String password) throws EmptyResultDataAccessException {
        User user = userDao.findByUsernameAndPassword(username,password);
        return user;
    }
}
